﻿/**
 * 加載圖片并按比例縮放
 * 
 * @author Luodong
 * @email luo4521@online.net.tw
 * 2010-2-4 22:32
 */
package com.addcn.texas.utils
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import flash.system.ApplicationDomain;
	
	import com.addcn.common.utils.GameLoader;
	import com.addcn.common.event.ParamEvent;
	
	public class GetPhoto extends EventDispatcher
	{
		public static var COMPLETE:String = "complete";
		public static var IO_ERROR:String = "ioError";
		
		private var _parent : Object;
		private var _url : String;
		private var _pic : Bitmap;
		private var _x : int;
		private var _y : int;
		private var _w : int;
		private var _h : int;
		
		public function GetPhoto() : void {	};
		
		public function setArgument(r_url : String , r_w:int = 55, r_h:int = 55, r_x : int = 0, r_y : int = 0) : void
		{
			this._url = r_url;
			this._w = r_w;
			this._h = r_h;
			this._x = r_x;
			this._y = r_y;			
		}
		
		public function setParent(r_parent: Object) : void
		{
			this._parent = r_parent;
		}	
		
		public function load() : void
		{
			_loadPhoto();
		}
		public function getPic() : Bitmap
		{
			return this._pic;
		}
		private function _loadPhoto() : void
		{
			var _loader : GameLoader = new GameLoader(ApplicationDomain.currentDomain);
			_loader.addEventListener(GameLoader.COMPLETE, _loadCompleteHalder);
			_loader.addEventListener(GameLoader.IO_ERROR, _loadErrHandler);
			_loader.addEventListener(GameLoader.TIME_OUT, _loadErrHandler);
			_loader.add(this._url, { id:"photo", name : 'photo' } );
			_loader.start();			
		}
		
		private function _loadCompleteHalder(evt : Event) : void {
			var _content = evt.target.getFile("photo") as DisplayObject;		
			
			_pic = PicBitMap.getPicBitMap(_content, this._w, this._h, true );
			_pic.x = this._x;
			_pic.y = this._y;
			if(this._parent != null){
				this._parent.addChild(_pic);
			}		
			_remove(evt);
			_sendEvent("complete");
									
		}

		private function _loadErrHandler(evt : Event) : void
		{
			_remove(evt);
			_sendEvent("complete");			
		}		
		
		private function _sendEvent(r_event: String = "err") : void
		{
			var _event :ParamEvent;
			if(r_event == "complete"){
				_event  = new ParamEvent(GetPhoto.COMPLETE, { pic : this._pic } );
			}else {
				_event  = new ParamEvent(GetPhoto.IO_ERROR);
			}						
			dispatchEvent(_event);
		}
		
	
		private function _remove(evt) : void
		{
			evt.target.destroyFileTemp;			
			evt.target.removeEventListener(GameLoader.COMPLETE, _loadCompleteHalder);
			evt.target.removeEventListener(GameLoader.IO_ERROR, _loadErrHandler);
			evt.target.removeEventListener(GameLoader.TIME_OUT, _loadErrHandler);
			this._parent = null;
		}
	}
	
}
